#!coding=utf-8
from xml.etree import ElementTree
from django.http import HttpResponse
from weixin.api import comprocs
from weixin.api.common import getJssdkTicket, getWebAccToken, getWXCustinfo
from weixin.api.sign import Sign
import json
from shop.models import Order, CardItem, CardInfo, CardTxn
from weixin.pay.payutil import getpaysign
from weixin.models import User
import time
from django.core.exceptions import ObjectDoesNotExist
from weixin.send.tempmsg import sendpaycardinfotocust, sendpayinfotocust
from django.core.cache import cache

def callback(request):  
    """
    微信的回调信息
    """
    print "weixin in "
    msg = {}
    if request.body == "":
        echoStr = request.GET.get("echostr", "NULL")
        return HttpResponse(echoStr)
    
    xml_elem = ElementTree.fromstring(request.body)
    
    for child in xml_elem:
        for child_2 in child:
            msg[child_2.tag] = child_2.text
        msg[child.tag] = child.text
    
    msgType=msg.get("MsgType")
    
    proc_function = getattr(comprocs,"proc_%s"%msgType)
        
    if callable(proc_function):
        return proc_function(msg)
    else:
        return HttpResponse("XML ERROR")
    

def getticket(request):
    url=request.GET.get("url");
    ticket=getJssdkTicket();
    sign = Sign(ticket, url)
    msg=sign.sign();
    print msg
    encodedjson = json.dumps(msg)
    return HttpResponse(encodedjson)
 
def getopenid(request):
    code=request.POST.get("code");
    openid=request.session.get('openid',False)
    if openid == False:
        openid=getWebAccToken(code)
        request.session['openid']=openid
    res={"openid":openid}
    encodedjson = json.dumps(res)
    return HttpResponse(encodedjson)
   
def getpayparm(request):
    orderid=request.POST.get("orderid");
    order=Order.objects.get(id=int(orderid));
    ip = request.META['REMOTE_ADDR']
    #微信支付的单位是分，所以要*100，'1'表示是订单支付
    data=getpaysign('1',order.open_id,order.id,ip,int(order.act_price*100));
    return HttpResponse(json.dumps(data));

def getcardpayparm(request):
    carditemid=request.POST.get("carditemid");
    carditem=CardItem.objects.get(id=int(carditemid));
    cardinfo=CardInfo.objects.get(id=int(carditem.cardinfo.id));
    ip = request.META['REMOTE_ADDR']
    #微信支付的单位是分，所以要*100，'2'表示是卡券支付
    
    data=getpaysign('2',carditem.openid,carditem.id,ip,int(cardinfo.face_value*100));
    return HttpResponse(json.dumps(data));

def payorder(request):
    orderid=request.POST.get("orderid");
    order=Order.objects.get(id=int(orderid));
    try:
        user=User.objects.get(openid=order.open_id)
        if order.price - user.balance > 0 : 
            res={"code":"error","error":"账户余额不足！"}
            encodedjson = json.dumps(res)
            return HttpResponse(encodedjson)
        else:
            user.balance=user.balance-order.act_price
            user.save()
            order.status='已支付'
            order.pay_sign='账户余额支付'
            order.save()
            sendpayinfotocust(order.open_id,str(order.id),order.pay_sign)
            
            res={"code":"true","true":"已通过账户余额支付！"}
            encodedjson = json.dumps(res)
            return HttpResponse(encodedjson)
    except:
    
        res={"code":"error","error":"账户余额不足！"}
        encodedjson = json.dumps(res)
        return HttpResponse(encodedjson)
    
def getCustinfo(request):
    openid=request.POST.get("openid");
    res = getWXCustinfo(openid)
    return HttpResponse(json.dumps(res))

# res=getWXCustinfo("oLu6SwrT0HpPwyUHp40MSIqVTX90")
# print json.dumps(res).encode("utf-8")
# print type(getWXCustinfo("oLu6SwrT0HpPwyUHp40MSIqVTX90"))

def getpayrespone(request):
    msg={}
    xml_elem = ElementTree.fromstring(request.body)
    for child in xml_elem:
        msg[child.tag] = child.text
#1表示是订单支付
    if msg["out_trade_no"].startswith("1"):
        if msg["result_code"]=="SUCCESS":
            transno=msg["out_trade_no"][17:]
            order=Order.objects.get(id=int(transno));
            order.status="已支付";
            order.pay_sign=msg["transaction_id"]
            order.save();
            
            user=User.objects.get(openid=order.open_id);
            user.score=user.score+order.act_price
            user.save()
            sendpayinfotocust(order.open_id,str(order.id),order.pay_sign)
            res="<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>"
            return HttpResponse(res);
        else:
            return HttpResponse("error");  
#2表示是卡券支付
    elif msg["out_trade_no"].startswith("2"):
        if msg["result_code"]=="SUCCESS":
            transno=msg["out_trade_no"][17:]
            
            carditem=CardItem.objects.get(id=int(transno));
            cardinfo=CardInfo.objects.get(id=int(carditem.cardinfo.id));
            carditem.status="已支付";
            carditem.pay_sign=msg["transaction_id"]
            carditem.save();
            
            tmpcardtxn=CardTxn(openid=msg["openid"],card=cardinfo.name);
            tmpcardtxn.save();
            
            try:
                user=User.objects.get(openid=carditem.openid);
                user.balance=user.balance+cardinfo.actual_value
                user.score=user.score+cardinfo.face_value
                user.save();
            except ObjectDoesNotExist:
                usertmp=User(openid=carditem.openid,score=cardinfo.face_value,balance=cardinfo.actual_value,subscribe_time=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
                usertmp.save()
            
            sendpaycardinfotocust(carditem.openid,str(carditem.price))
            res="<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>"
            return HttpResponse(res);
        else:
            return HttpResponse("error");  

# <xml>
#   <appid><![CDATA[wx8888888888888888]]></appid>  
#   <bank_type><![CDATA[CFT]]></bank_type>  
#   <fee_type><![CDATA[CNY]]></fee_type>  
#   <is_subscribe><![CDATA[Y]]></is_subscribe>  
#   <mch_id><![CDATA[10012345]]></mch_id>  
#   <nonce_str><![CDATA[60uf9sh6nmppr9azveb2bn7arhy79izk]]></nonce_str>  
#   <openid><![CDATA[ou9dHt0L8qFLI1foP-kj5x1mDWsM]]></openid>  
#   <out_trade_no><![CDATA[wx88888888888888881414411779]]></out_trade_no>  
#   <result_code><![CDATA[SUCCESS]]></result_code>  
#   <return_code><![CDATA[SUCCESS]]></return_code>  
#   <sign><![CDATA[0C1D7F2534F1473247550A5A138F0CEB]]></sign>  
#   <sub_mch_id><![CDATA[10012345]]></sub_mch_id>  
#   <time_end><![CDATA[20141027200958]]></time_end>  
#   <total_fee>1</total_fee>  
#   <trade_type><![CDATA[JSAPI]]></trade_type>  
#   <transaction_id><![CDATA[1002750185201410270005514026]]></transaction_id> 
# </xml>
#     

def getAcctSts(request):
    userparm=request.GET.get("loginparm");
    if userparm!="":
        if cache.get(userparm) != None :
            return HttpResponse(json.dumps({"logsts":cache.get(userparm)}))
        else:
            return HttpResponse(json.dumps({"logsts":"N"}))
                                
def setAcctStsLogin(request):
    userparm=request.GET.get("loginparm");
    openid=request.GET.get("openid");
    if cache.get(userparm) == None :
        cache.add(userparm,openid,300)
        return HttpResponse(json.dumps({"code":"success"}))
    else:
        cache.set(userparm,openid)
        return HttpResponse(json.dumps({"code":"success"}))
    
    
    
    
    
    
    